/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from "axios";
import { store } from "../store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
axios.defaults.timeout = 3000000000000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
//axios.defaults.withCredentials = true;
//HTTPrequest拦截
axios.interceptors.request.use(
  (config) => {
    //console.log(config)
    // 缓存最近30次的数据请求参数，做为excel导出数据用
    // console.log(config,'config')
    if (config.method == "get" || config.url.indexOf("custmerform/data/") != -1) {
      store.dispatch("app/addRequest", { url: config.url, params: config.params, data: config.data });
    }

    if (config.url.indexOf("http://") == -1 && config.url.indexOf("https://") == -1) {
      config.url = `${window.$apiUrl}${config.url}`;
    }

    NProgress.start(); // start progress bar
    const meta = config.meta || {};
    const isToken = meta.isToken === false;

    const hasProjectId = meta.hasProjectId === true;

    if (store.getters.token && !isToken) {
      config.headers.token = store.getters.token; // 让每个请求携带token--['token']为自定义key 请根据实际情况自行修改
    } else if (!isToken) {
      Message({
        message: "没有登录信息",
        type: "error",
      });
      store.dispatch("organization/user/fedLogOut").then(() => window.$router.push({ path: "/login" }));
      return Promise.reject(new Error("没有登录信息"));
    }

    if (hasProjectId) {
      if (store.getters.project == null) {
        Message({
          message: "没有项目信息请重新选择项目",
          type: "error",
        });
        window.$router.push({ path: "/tool/project/index" });
        return Promise.reject(new Error("没有项目信息"));
      }
      if (store.getters.project.f_Id) {
        config.headers.learunprojectId = store.getters.project.f_Id;
      } else {
        Message({
          message: "没有项目信息请重新选择项目",
          type: "error",
        });
        window.$router.push({ path: "/tool/project/index" });
        return Promise.reject(new Error("没有项目信息"));
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    NProgress.done();
    const status = Number(res.status) || 200;
    const message = res.data.info || "未知错误";

    //如果是401则跳转到登录页面
    if (status === 401)
      store.dispatch("organization/user/fedLogOut").then(() => window.$router.push({ path: "/login" }));
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
      Message({
        message: message,
        type: "error",
      });
      return Promise.reject(new Error(message));
    } else if (res.data.code && res.data.code != 200) {
      if (res.data.code === 401) {
        Message({
          message: message,
          type: "warning",
        });
        store.dispatch("organization/user/fedLogOut").then(() => window.$router.push({ path: "/login" }));
      } else {
        Message({
          message: message,
          type: "error",
        });
      }

      return Promise.reject(new Error(message));
    }
    return res;
  },
  (error) => {
    //if(error没有项目信息)
    NProgress.done();
    if (error.message != "没有项目信息") {
      window.$router.push({ path: "/500" });
    }

    return Promise.reject(new Error(error));
  }
);

window.$crud = (url, hasProjectId = false) => {
  return {
    getPage: (params) => {
      return axios({
        url: `${url}/page`,
        method: "get",
        params,
        meta: {
          hasProjectId,
        },
      });
    },
    getList: (params) => {
      return axios({
        url: `${url}s`,
        method: "get",
        params,
        meta: {
          hasProjectId,
        },
      });
    },
    get: (id) => {
      return axios({
        url: `${url}/${id}`,
        method: "get",
        meta: {
          hasProjectId,
        },
      });
    },
    add: (data) => {
      return axios({
        url: `${url}`,
        method: "post",
        data,
        meta: {
          hasProjectId,
        },
      });
    },
    update: (id, data) => {
      return axios({
        url: `${url}/${id}`,
        method: "put",
        data,
        meta: {
          hasProjectId,
        },
      });
    },
    remove: (id) => {
      return axios({
        url: `${url}/${id}`,
        method: "delete",
        meta: {
          hasProjectId,
        },
      });
    },
  };
};

export default axios;
